package com.example.pagergallery

import android.content.ContentValues
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.core.view.get
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import kotlinx.coroutines.*
import uk.co.senab.photoview.PhotoView
import java.util.jar.Manifest

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [PagerPhotoFragment.newInstance] factory method to
 * create an instance of this fragment.
 */

const val REQUEST_WRITE_EXTERNAL_STORAGE = 1
class PagerPhotoFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_pager_photo, container, false)
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment PagerPhotoFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            PagerPhotoFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val photoList = arguments?.getParcelableArrayList<PhotoItem>("PHOTO_LIST")   //得到photo_list
        val viewPager2 = view.findViewById<ViewPager2>(R.id.viewPager2)
        PagerPhotoListAdapter().apply {
            viewPager2.adapter = this
            submitList(photoList)   //将photo传过来

        }

        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {    //选中某个页面要做的事情
                super.onPageSelected(position)
                view.findViewById<TextView>(R.id.photoTag).text = getString(R.string.photo_tag,position+1,photoList?.size)
                //view.findViewById<TextView>(R.id.photoTag).text = "${position+1}/${photoList?.size}"   //因为在string.xml中添加了资源（photo_tag），所以用上面这行更严谨，不会警告
            }
        })

        viewPager2.setCurrentItem(arguments?.getInt("PHOTO_POSITION")?:0,false)   //给一个序号传递过来  两个参数  序号，是否平滑的滚动

        //保存照片到手机  首先添加权限   由于即使添加了权限，手机也没有打开，需要创建对话框让手机用户同意开启权限（动态申请）
        view.findViewById<ImageView>(R.id.imageViewDownload).setOnClickListener {
            if (Build.VERSION.SDK_INT<29 && ContextCompat.checkSelfPermission(requireContext(),
                    //SDK.INT:当前手机运行的版本  如果api版本>29  权限默认允许
                    //android10之后不是不要，是这个权限就取消了，不让写数据到当前APP以外的文件夹去，类似IOS把文件读写权限控制得更严了
                    //安卓10 存储权限变了，程序只能访问自己的内容，存储媒体要用特定api
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED) {
                requestPermissions(arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    REQUEST_WRITE_EXTERNAL_STORAGE)   //弹出对话框  向用户请求权限
            }else{   //如果版本足够  则直接下载
                viewLifecycleOwner.lifecycleScope.launch {   //让我们的副线程（IO线程）在lifecycleScope的范围中执行  如果fragment的生命周期被摧毁，副线程会自动终止
                    savePhoto()
                }
            }
        }
    }

    override fun onRequestPermissionsResult(    //动态权限请求
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode){
            REQUEST_WRITE_EXTERNAL_STORAGE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    //savePhoto()    //判断权限通过  下载图片
                    viewLifecycleOwner.lifecycleScope.launch {   //让我们的副线程（IO线程）在lifecycleScope的范围中执行  如果fragment的生命周期被摧毁，副线程会自动终止
                        savePhoto()
                    }
                }else{
                    Toast.makeText(requireContext(),"存储失败",Toast.LENGTH_SHORT).show()   //权限没通过，提示存储失败
                }
            }
        }
    }

    //图片下载
    private suspend fun savePhoto() {   //一搬不会放到主线程，如果图片较大将会拥堵线程   suspend:允许该方法在其他线程挂起
        withContext(Dispatchers.IO){     //Main：主线程   IO：输入输出这些耗时操作放入的IO线程
            val viewPager2 = view?.findViewById<ViewPager2>(R.id.viewPager2)
            val holder = (viewPager2?.get(0) as RecyclerView).findViewHolderForAdapterPosition(viewPager2.currentItem)
                    as PagerPhotoViewHolder   //在RecyclerView中找到ViewHolder的位置  然后类型从普通的ViewHolder转换为PagerPhotoViewHolder
            val bitmap = holder.itemView.findViewById<PhotoView>(R.id.pagerPhoto).drawable.toBitmap()   //找到pagerPhoto，找到drawable，找到位图

            //delay(5000)    //延时图片下载进程

            //API版本低于29   insertImage将不可用，不让我们封装了(其实能用，但被淘汰了)
            /*if (MediaStore.Images.Media.insertImage(requi下reContext().contentResolver,bitmap,"","") == null){   //MediaStore：系统用于管理媒体共享区的一个管理器，相当于一个数据库
                  Toast.makeText(requireContext(),"存储失败",Toast.LENGTH_SHORT).show()
              }else{
                  Toast.makeText(requireContext(),"存储成功",Toast.LENGTH_SHORT).show()
              }   */

            //API版本高于29的写法  当前版本为32
            //第一步，创建一个保存的路径Uri
            val saveUri = requireContext().contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                ContentValues()    //（图片路径，具体的操作  可以不做具体操作）
            )?:kotlin.run {
                Toast.makeText(requireContext(),"存储失败",Toast.LENGTH_SHORT).show()
                return@withContext
            }
            requireContext().contentResolver.openOutputStream(saveUri).use {     //openOutputStream:打开一个输出流，将uri写入进去   use:会将流自动关闭   不用写apply等手动关闭
                if (bitmap.compress(Bitmap.CompressFormat.PNG,0,it)){     //(压缩格式，压缩率，输出流)
                    MainScope().launch { Toast.makeText(requireContext(),"存储成功",Toast.LENGTH_SHORT).show() }     //Toast只能运行在主线程，在副线程会导致崩溃，这里用MainScope().launch
                }else{
                    MainScope().launch { Toast.makeText(requireContext(),"存储失败",Toast.LENGTH_SHORT).show() }     //MainScope就是主线程中的Scope
                }
            }
        }



    }

}